<?php
namespace Home\Controller;
use Think\Controller;

//消息控制器
class NewsController extends Controller
{
    public function index()
    {
        //判断用户是否登录
        if (empty($_SESSION['user'])) {
            $this->error('请登录-_-!');
        }
        
        $id = $_SESSION['user']['uid'];
        M('news')->create();
        $news = M('news');
        if (empty($_GET['p'])) {
            $_GET['p'] = 1;
        }
        //分页
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $list = $news->table('baidu_news n,baidu_user_info ui')->field('n.id,n.fuid,n.content,n.time,n.status,n.name,n.suid,ui.path')->where("n.suid='$id' AND n.fuid=ui.uid")->order('n.id desc')->page($_GET['p'].',5')->select();

        $this->assign('list',$list);// 赋值数据集
        $count = $news->where("suid='$id'")->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,5);// 实例化分页类 传入总记录数和每页显示的记录数
        $Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出

        //查询消息个数
        $count = $news->where("suid='$id' and status='1'")->count();
        $this->assign('count',$count);

        $this->display('News/index');
    }

    //发送消息
    public function send()
    {
        //判断是否有未填信息
        if (empty($_POST['name']) || empty($_POST['text'])) {
            $this->error('请完善您发送的信息!');
        }

        //判断接收信息人是否存在
        M('user')->create();
        $name = $_POST['name'];
        $uid = M('user')->where("name='$name'")->field('id')->find();
        $uid = $uid['id'];
        // dump($uid);exit;
        if ($uid > 0) {
            M('user_info')->create();
            $user_info = M('user_info')->where("uid='$uid'")->select();
            $data['fuid'] = $_SESSION['user']['uid'];
            $data['content'] = $_POST['text'];
            $data['time'] = date('Y-m-d H:i:s');
            $data['status'] = 1;
            $data['name'] = $_SESSION['user']['name'];
            $data['picture'] = $user_info[0]['path'];
            $data['suid'] = $uid;
            // dump($data);
            M('news')->create();
            if (M('news')->add($data)>0) {
                $this->success('发送成功!');
            }else{
                $this->error('发送失败!');
            }
        }else{
            $this->error('用户不存在!');
        }
    }

    //消息状态控制
    public function status()
    {
        $content = $_POST['content'];
        $status['status'] = 2;
        M('news')->create();
        M('news')->where("content='$content'")->save($status);
    }

    //删除消息
    public function del()
    {
        $nid = $_POST['nid'];
        M('news')->create();
        M('news')->delete($nid);
        $this->ajaxReturn();
    }
}

